package cn.aiweiyi.qingjing.coupon.template.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 青衿
 * @Date 2020/11/17 11:10
 * 用于执行异步操作的线程池配置
 **/

@Slf4j
@EnableAsync
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {

    @Bean
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();//创建一个基于线程池的执行器
        executor.setCorePoolSize(10);//池中线程10个
        executor.setMaxPoolSize(20);//最大20哥线程
        executor.setQueueCapacity(20);//队列容量20
        executor.setThreadNamePrefix("kt_coupon_async_");//线程前缀
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.setRejectedExecutionHandler(
                new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();//初始化
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
                throwable.printStackTrace();
                ;
                log.error("异步出错:{},方法:{},参数:{}",
                        throwable.getMessage(), method.getName(),
                        JSON.toJSONString(objects));
                //发送邮件或短信,或者做进一步的处理
            }
        };
    }
}
